package com.example;

import java.util.Random;

public class UnsafeSingleton {
    private static UnsafeSingleton instance = null;
    private Double data = null;

    private UnsafeSingleton() {
        double tmp = 0;
        for (int i = 0; i < 10000000; i++) {
            double x = new Random().nextInt(10000000) / (new Random().nextInt(10000000) + 1);
            tmp += x;
        }
        data = new Double(tmp);
    }

    public static UnsafeSingleton getInstance() {
        if (instance == null) {
            synchronized (UnsafeSingleton.class) {
                if (instance == null) {
                    instance = new UnsafeSingleton();
                }
            }
        }
        return instance;
    }

    public static void main(String[] args) throws InterruptedException {
        Runnable r = new Runnable() {
            @Override
            public void run() {
                UnsafeSingleton unsafeSingleton = UnsafeSingleton.getInstance();
                if (unsafeSingleton == null || unsafeSingleton.getData() == null) {
                    System.out.println(unsafeSingleton + " " + unsafeSingleton.getData());
                    System.exit(1);
                }
            }
        };
        for (int i = 0; i < 8000; i++) {
            try {
                Thread t = new Thread(r);
                t.start();
            } catch (Exception e) {
                e.printStackTrace();
                break;
            } catch (Error e) {
                e.printStackTrace();
                break;
            }
        }
        System.out.println("done" + System.currentTimeMillis());
    }

    public Double getData() {
        return data;
    }
}
